import React, { useState } from 'react'
import { 
  Card, 
  Row, 
  Col, 
  Descriptions, 
  Tag, 
  Button, 
  Space, 
  Alert,
  Tabs,
  Table,
  Progress,
  Statistic,
} from 'antd'
import { 
  MonitorOutlined, 
  SyncOutlined, 
  CheckCircleOutlined,
  WarningOutlined,
  InfoCircleOutlined,
  SettingOutlined,
} from '@ant-design/icons'
import { useQuery } from 'react-query'
import { shardTaskApi } from '../services/shardTask'

const { TabPane } = Tabs

const SystemStatus: React.FC = () => {
  const [activeTab, setActiveTab] = useState('system')

  // 获取分片策略信息
  const { data: strategies, isLoading: strategiesLoading } = useQuery(
    'shardingStrategies',
    shardTaskApi.getShardingStrategies
  )

  // 获取分片处理器信息
  const { data: handlers, isLoading: handlersLoading } = useQuery(
    'shardHandlers',
    shardTaskApi.getShardHandlers
  )

  // 获取集群节点信息
  const { data: clusterNodes, isLoading: nodesLoading } = useQuery(
    'clusterNodes',
    shardTaskApi.getClusterNodes
  )

  // 系统健康检查
  const getSystemHealth = () => {
    const checks = [
      {
        name: '集群连接',
        status: (clusterNodes?.total_nodes || 0) > 0 ? 'success' : 'warning',
        message: `发现 ${clusterNodes?.total_nodes || 0} 个活跃节点`,
        details: `运行分片: ${clusterNodes?.total_active_shards || 0} 个`
      },
      {
        name: '分片策略',
        status: (strategies?.strategies?.length || 0) >= 4 ? 'success' : 'warning',
        message: `支持 ${strategies?.strategies?.length || 0} 种分片策略`,
        details: '哈希、范围、轮询、自定义分片'
      }
    ]
    
    return checks
  }

  const healthChecks = getSystemHealth()

  // 处理器状态表格列
  const handlerColumns = [
    {
      title: '处理器名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string) => (
        <Tag color="blue">{text.replace('demo_', '').replace(/_/g, ' ')}</Tag>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '参数',
      dataIndex: 'parameters',
      key: 'parameters',
      render: (params: Record<string, string>) => (
        <Space direction="vertical" size="small">
          {Object.entries(params).map(([key, value]) => (
            <Tag key={key}>
              {key}: {value}
            </Tag>
          ))}
        </Space>
      ),
    },
    {
      title: '状态',
      key: 'status',
      render: () => (
        <Tag color="green" icon={<CheckCircleOutlined />}>
          就绪
        </Tag>
      ),
    },
  ]

  // 分片策略表格列
  const strategyColumns = [
    {
      title: '策略名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string) => <Tag color="purple">{text}</Tag>,
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '适用场景',
      dataIndex: 'use_case',
      key: 'use_case',
    },
  ]

  // 性能统计表格列
  const perfColumns = [
    {
      title: '处理器',
      dataIndex: 'handler_name',
      key: 'handler_name',
      render: (text: string) => (
        <Tag color="blue">{text.replace('demo_', '').replace(/_/g, ' ')}</Tag>
      ),
    },
    {
      title: '执行次数',
      dataIndex: 'total_executions',
      key: 'total_executions',
      sorter: (a: any, b: any) => a.total_executions - b.total_executions,
    },
    {
      title: '成功率',
      dataIndex: 'success_rate',
      key: 'success_rate',
      render: (rate: string) => {
        const percent = parseFloat(rate)
        return (
          <div>
            <Progress 
              percent={percent} 
              size="small" 
              strokeColor={percent >= 90 ? '#52c41a' : percent >= 70 ? '#faad14' : '#ff4d4f'}
            />
            <small>{rate}</small>
          </div>
        )
      },
      sorter: (a: any, b: any) => parseFloat(a.success_rate) - parseFloat(b.success_rate),
    },
    {
      title: '平均耗时',
      dataIndex: 'avg_duration',
      key: 'avg_duration',
    },
    {
      title: '成功/失败',
      key: 'success_fail',
      render: (record: any) => (
        <Space>
          <Tag color="green">{record.success_count}</Tag>
          <Tag color="red">{record.failed_count}</Tag>
        </Space>
      ),
    },
  ]

  return (
    <div>
      <div style={{ marginBottom: 24 }}>
        <h1 style={{ fontSize: 24, fontWeight: 'bold', marginBottom: 8 }}>
          <MonitorOutlined style={{ marginRight: 8, color: '#1890ff' }} />
          系统状态监控
        </h1>
        <p style={{ color: '#666', fontSize: 14 }}>
          查看系统运行状态、组件健康情况和性能指标
        </p>
      </div>

      <Tabs activeKey={activeTab} onChange={setActiveTab}>
        <TabPane tab="系统状态" key="system">
          {/* 健康检查 */}
          <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
            <Col span={24}>
              <Card title="系统健康检查">
                <Row gutter={[16, 16]}>
                  {healthChecks.map((check, index) => (
                    <Col xs={24} sm={12} md={6} key={index}>
                      <Alert
                        message={check.name}
                        description={
                          <div>
                            <div>{check.message}</div>
                            <small style={{ color: '#666' }}>{check.details}</small>
                          </div>
                        }
                        type={check.status as any}
                        showIcon
                        style={{ height: '100%' }}
                      />
                    </Col>
                  ))}
                </Row>
              </Card>
            </Col>
          </Row>

          {/* 系统信息 */}
          <Row gutter={[16, 16]}>
            <Col xs={24} lg={12}>
              <Card title="集群状态" loading={nodesLoading}>
                <Row gutter={16}>
                  <Col span={8}>
                    <Statistic
                      title="活跃节点"
                      value={clusterNodes?.total_nodes || 0}
                      valueStyle={{ color: '#1890ff' }}
                    />
                  </Col>
                  <Col span={8}>
                    <Statistic
                      title="运行分片"
                      value={clusterNodes?.total_active_shards || 0}
                      valueStyle={{ color: '#722ed1' }}
                    />
                  </Col>
                  <Col span={8}>
                    <Statistic
                      title="平均负载"
                      value={clusterNodes ? (clusterNodes.total_active_shards / Math.max(clusterNodes.total_nodes, 1)).toFixed(1) : 0}
                      suffix="分片/节点"
                      valueStyle={{ color: '#fa8c16' }}
                    />
                  </Col>
                </Row>
                <div style={{ marginTop: 16 }}>
                  <Descriptions column={1} size="small">
                    <Descriptions.Item label="更新时间">
                      {clusterNodes?.timestamp ? new Date(clusterNodes.timestamp).toLocaleString() : '-'}
                    </Descriptions.Item>
                  </Descriptions>
                </div>
              </Card>
            </Col>
          </Row>
        </TabPane>

        <TabPane tab="组件状态" key="components">
          <Row gutter={[16, 16]}>
            <Col span={24}>
              <Card title="分片处理器状态" loading={handlersLoading}>
                <Alert
                  message="处理器注册情况"
                  description={`系统已注册 ${handlers?.total_handlers || 0} 个分片处理器，包括 ${handlers?.handlers?.length || 0} 个可用处理器`}
                  type="info"
                  showIcon
                  style={{ marginBottom: 16 }}
                />
                <Table
                  columns={handlerColumns}
                  dataSource={handlers?.handlers || []}
                  rowKey="name"
                  pagination={false}
                  size="small"
                />
              </Card>
            </Col>
          </Row>

          <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
            <Col span={24}>
              <Card title="分片策略支持" loading={strategiesLoading}>
                <Table
                  columns={strategyColumns}
                  dataSource={strategies?.strategies || []}
                  rowKey="name"
                  pagination={false}
                  size="small"
                />
              </Card>
            </Col>
          </Row>
        </TabPane>
      </Tabs>
    </div>
  )
}

export default SystemStatus